//
//  MoreLivingViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2017/4/10.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "MoreLivingViewController.h"
#import "WatchViewController.h"
#import "BuyViewController.h"
#import "FlowLayout.h"
#import "StarLivingListCell.h"
#import "WatchLiveTipView.h"
#import "LiveListModel.h"

@interface MoreLivingViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,WatchLiveTipViewDelegate> {
    NSMutableArray *_livelistArr;
    int _page;//当前页数
    int _totalPage;//总页数
}
@property (nonatomic, strong) UICollectionView *livingCollectionView;
@property (nonatomic, strong) FlowLayout *flowLayout;
/**
 判断余额是否充足 YES:充足 NO:不足
 */
@property (nonatomic, assign) BOOL BalanceTag;
@property (nonatomic, strong) WatchLiveTipView *watchTipView;
@end

@implementation MoreLivingViewController
static NSString *starlivingListCellID = @"starlivingListCellID";

#pragma mark -- 明星直播列表请求
- (void)StarlistRequest {
    NSDictionary *dic = @{
                          @"udid":User_ID,
                          @"token":TOKEN,
                          @"page":@"0",
//                          @"amount":@"1",
                          };
    NSString *urlString = [TEST_URL stringByAppendingString:kLiveList];
    [NetworkTools postReqeustWithParams:dic UrlString:urlString successBlock:^(id responseObject) {
        [self.livingCollectionView.mj_header endRefreshing];
        if (_livelistArr.count>0) {
            [_livelistArr removeAllObjects];
        }
        NSArray *array = responseObject[@"data"][@"list"];
        for (NSDictionary *dict in array) {
            LiveListModel *model = [[LiveListModel alloc] initWithDict:dict];
            [_livelistArr addObject:model];
        }
//        self.flowLayout.array = [NSArray arrayWithArray:_livelistArr];
        [self.flowLayout invalidateLayout];
        [self.livingCollectionView reloadData];
    } failureBlock:^(NSError *error) {
        [self.livingCollectionView.mj_header endRefreshing];
    } showHUD:NO];
}


#pragma mark -- 支付观看看直播费用
- (void)payLiveWithChannel:(NSString *)channel Price:(NSString *)price S_uid:(NSString *)s_uid {
    NSDictionary *paramDic = @{
                               @"udid":User_ID,
                               @"token":TOKEN,
                               @"channel":channel,
                               @"price":price
                               };
    NSString *urlString = [TEST_URL stringByAppendingString:kPayLive];
    [NetworkTools postReqeustWithParams:paramDic UrlString:urlString successBlock:^(id responseObject) {
        [self PulladdressRequestWithRoomId:channel S_uid:s_uid];
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}


#pragma mark -- 查询账户余额接口
- (void)BalanceRequestWithLiveListModel:(LiveListModel *)listModel {
    NSDictionary *dict = @{
                           @"udid":User_ID,
                           @"token":TOKEN
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kBalance];
    [self showHUDInView:self.view title:nil];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [self hideHUD];
        NSString *balance = responseObject[@"data"][@"u_balance"];
        if ([balance intValue] < [listModel.s_price intValue]) {//余额不足
            self.BalanceTag = NO;
        } else {//余额充足
            self.BalanceTag = YES;
        }
        [self creatWatchTipViewWith:self.BalanceTag LiveListModel:listModel Balance:balance];
    } failureBlock:^(NSError *error) {
        [self hideHUD];
    } showHUD:NO];
}

#pragma mark -- 获取观看直播地址
- (void)PulladdressRequestWithRoomId:(NSString *)roomid S_uid:(NSString *)s_uid {
    NSDictionary *dic = @{
                          @"udid":User_ID,
                          @"token":TOKEN,
                          @"channel":roomid,
                          @"status":@"1" //1表示进入直播间
                          };
    NSString *urlString = [TEST_URL stringByAppendingString:kWatchlive];
    [NetworkTools postReqeustWithParams:dic UrlString:urlString successBlock:^(id responseObject) {
        NSString *pullUrl = responseObject[@"data"][@"url"][1];
        
        WatchViewController *watchVc = [[WatchViewController alloc] init];
        watchVc.roomid = roomid;
        watchVc.chatroomid = roomid;
        watchVc.s_uid = s_uid;
        watchVc.pullUrl = pullUrl;
        [self presentViewController:watchVc animated:YES completion:nil];
        
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

#pragma mark -- watchTipView
- (void)creatWatchTipViewWith:(BOOL)BalanceTag LiveListModel:(LiveListModel*)listModel Balance:(NSString *)balance {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.watchTipView = [[NSBundle mainBundle] loadNibNamed:@"WatchLiveTipView" owner:self options:nil].lastObject;
    self.watchTipView.delegate = self;
    self.watchTipView.livelistModel = listModel;
    self.watchTipView.balance.text = [NSString stringWithFormat:@"您的账户余额 : %@L币",balance];
    [window addSubview:self.watchTipView];
    self.watchTipView.backgroundColor = kRGB(0, 0, 0, 0.6);
    [self.watchTipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(window);
    }];
    
    //设置余额不足的隐藏
    if (self.BalanceTag == YES) {
        self.watchTipView.NoPayNotice.hidden = YES;
        [self.watchTipView.watchBtn setTitle:@"观看直播" forState:UIControlStateNormal];
    } else {
        self.watchTipView.NoPayNotice.hidden = NO;
        [self.watchTipView.watchBtn setTitle:@"立即购买" forState:UIControlStateNormal];
    }
}

#pragma mark -- WatchTipViewDelegate

- (void)closeTipView {
    [self.watchTipView removeFromSuperview];
}

- (void)buyClickWithTipView:(WatchLiveTipView *)watchtipView LiveListModel:(LiveListModel*)liveListModel {
    if (self.BalanceTag == NO) {//去购买芝麻
        [self.watchTipView removeFromSuperview];
        BuyViewController *buyVC = [[BuyViewController alloc] init];
        buyVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:buyVC animated:YES];
    } else {//观看直播
        [self.watchTipView removeFromSuperview];
        [self payLiveWithChannel:liveListModel.l_channel Price:liveListModel.s_price S_uid:liveListModel.l_udid];
    }
}
/**
 *  停止刷新
 */
-(void)endRefresh{
    [self.livingCollectionView.mj_header endRefreshing];
    [self.livingCollectionView.mj_footer endRefreshing];
}

#pragma mark -- lazy
- (UICollectionView *)livingCollectionView {
    if (!_livingCollectionView) {
        self.flowLayout = [[FlowLayout alloc] init];
        [self.flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        _livingCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT - 64) collectionViewLayout:self.flowLayout];
        self.flowLayout.count = 12;
        [_livingCollectionView registerNib:[UINib nibWithNibName:@"StarLivingListCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:starlivingListCellID];
        _livingCollectionView.delegate = self;
        _livingCollectionView.dataSource = self;
        //默认block方法：设置下拉刷新
        __weak typeof(self) weakSelf = self;
        _livingCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _page = 0;
            [weakSelf StarlistRequest];
        }];
        _livingCollectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            _page++;
            if (_page == _totalPage + 1) {
                weakSelf.livingCollectionView.mj_footer.state = MJRefreshStateNoMoreData;
            } else {
                [weakSelf StarlistRequest];
            }
        }];
        [self.view addSubview:_livingCollectionView];
    }
    return _livingCollectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpUI];
    
    [self setNav];
    
    [self StarlistRequest];
}

- (void)setUpUI {
    self.livingCollectionView.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
     _livelistArr = [NSMutableArray arrayWithCapacity:1];
}


- (void)setNav {
   self.navigationItem.title = @"更多直播";
}

#pragma mark -- DataSource Delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _livelistArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    StarLivingListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:starlivingListCellID forIndexPath:indexPath];
    LiveListModel *model = _livelistArr[indexPath.row];
    cell.livelistModel = model;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((kSCREEN_WIDTH - 40)/2, (kSCREEN_WIDTH - 40)/2 + 30);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 15, 0, 15);//分别为上、左、下、右
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    LiveListModel *listModel = _livelistArr[indexPath.row];
    //查询账户余额
    [self BalanceRequestWithLiveListModel:listModel];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
